package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Account;
import model.Database;
import model.Encryption;
import model.IOFile;
import model.OptionMessenger;
import model.UICommand;
import ui.BusyDialog;
import view.LogginPanel;
import view.MainFrame;

public class LogginController implements ActionListener, FocusListener {
	private LogginPanel logginView;
	private MainFrame mainView;
	private ConfigureController configControl;

	public LogginController(MainFrame mainView) {
		this.mainView = mainView;
		this.logginView = new LogginPanel(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		switch (cmd) {
		case "pass":
			logginView.getBtnLoggin().doClick();
			break;
		case "loggin":
			loggin();
			break;
		case "exit":
			int answer = OptionMessenger.showQuestionDialog(logginView,
					"Thoát khỏi hệ thống?", "Thoát",
					OptionMessenger.QUESTION_MESSAGE);
			if (answer == OptionMessenger.OK_OPTION)
				System.exit(0);
			break;
		case "key":
			logginView.getPassField().requestFocus();
			break;
		case "config":
			if (configControl == null)
				configControl = new ConfigureController(logginView);
			configControl.show();
			break;
		case UICommand.GUESS_SESSION_CMD:
			try {
				Database.connect();
				switchWorkspace(new Account("Guess", "User"));
			} catch (ClassNotFoundException e1) {
				e1.printStackTrace(IOFile.getInstance());
			} catch (SQLException e1) {
				e1.printStackTrace(IOFile.getInstance());
				OptionMessenger.showMessageDialog(
						logginView,
						"Lỗi trong khi kết nối cơ sở dữ liệu\nChi tiết: "
								+ e1.getMessage(), "Lỗi",
						OptionMessenger.ERROR_MESSAGE);
			}
			break;
		}
	}

	private boolean checkValid(String name, String pass) {
		return (name.equals("") || pass.equals("")) ? false : true;
	}

	private void loggin() {
		String name = logginView.getUser();
		String pass = new String(logginView.getPass());
		if (!checkValid(name, pass)) {
			OptionMessenger.showMessageDialog(logginView,
					"Vui lòng nhập đầy đủ tên tài khoản và mật khẩu!",
					"Cảnh báo", OptionMessenger.WARNING_MESSAGE);
		} else {
			try {
				Connection connection = Database.connect();

				PreparedStatement preStm = connection
						.prepareStatement("SELECT * from account WHERE name = ?");
				preStm.setString(1, logginView.getUser());

				ResultSet rs = preStm.executeQuery();

				while (rs.next()) {
					String tmp = Encryption.encrypt(rs.getInt("id") + pass);
					if (tmp.equals(rs.getString("password"))) {
						if (rs.getBoolean("lock")) {
							OptionMessenger
									.showMessageDialog(
											logginView,
											"Tài khoản đã bị khóa không thể đăng nhập hệ thống",
											"Lỗi",
											OptionMessenger.WARNING_MESSAGE);
						} else {
							Account account = new Account(rs.getInt("id"),
									rs.getString("name"), rs.getString("exe"));
							switchWorkspace(account);
						}
						return;
					}
				}

				OptionMessenger.showMessageDialog(logginView,
						"Tài khoản hoặc mật khẩu không đúng", "Lỗi",
						OptionMessenger.ERROR_MESSAGE);
				logginView.setText();
			} catch (SQLException e) {
				e.printStackTrace(IOFile.getInstance());
				OptionMessenger.showMessageDialog(
						logginView,
						"Lỗi trong khi kết nối cơ sở dữ liệu\nChi tiết: "
								+ e.getMessage(), "Lỗi",
						OptionMessenger.ERROR_MESSAGE);
			} catch (ClassNotFoundException e) {
				e.printStackTrace(IOFile.getInstance());
			}
		}
	}

	public void switchWorkspace(final Account acc) {
		ActionListener action = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				mainView.display(acc, logginView.getImage());
				mainView.changeDisplay("workspace");
				logginView.getPassField().setText("");
			}
		};

		// size 450 - 199
		BusyDialog.showBusyDialog(mainView.getFrame(),
				"Đang khởi tạo giao diện", 450, 225, action, null);
	}

	@Override
	public void focusGained(FocusEvent e) {
		logginView.getTxtUser().selectAll();
		logginView.getPassField().selectAll();
	}

	@Override
	public void focusLost(FocusEvent e) {

	}

	public LogginPanel getView() {
		return this.logginView;
	}

}
